<template>
  <div>
    <el-tree
      ref="tree"
      v-loading="loading"
      :data="permissionList"
      :props="{ label: 'name' }"
      show-checkbox
      default-expand-all
      check-strictly
      node-key="id"
      style="min-height: 300px"
    />
    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="setRolesBtn"
        >确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { assignPremApi, getPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import { getRoleInfoApi } from '@/api/setting'
export default {
  name: 'AssignPermission',
  props: {
    uid: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      permissionList: [],
      loading: false,
      permIds: []
    }
  },
  created() {
    this.getPmList()
    this.getRoleInfo()
  },
  methods: {
    async getPmList() {
      const res = await getPermissionList()
      this.permissionList = tranListToTreeData(res.data)
    },
    async getRoleInfo() {
      this.loading = true
      const res = await getRoleInfoApi(this.uid)
      // 使用tree组件setCheckedKeys,将返回值渲染上去
      // 需要增加node-key属性
      this.$refs.tree.setCheckedKeys(res.data.permIds)
      this.loading = false
    },
    // 点击取消
    cancelButton() {
      this.$emit('close')
    },
    // 点击确定
    async setRolesBtn() {
      // 首先获取已选中的
      this.permIds = this.$refs.tree.getCheckedKeys()
      // 再发送请求
      const res = await assignPremApi({ id: this.uid, permIds: this.permIds })
      this.$message.success(res.message)
      // 关闭弹框
      this.$emit('close')
    }
  }
}
</script>
